﻿using Logic;
using Services.Input;
using UnityEngine;

namespace Hero
{
    public class HeroRotate : MonoBehaviour
    {
        public float Speed { get; set; }

        private IInputService _inputService;
        private int _groundMask;
        private Vector3 _playerToMouse;

        public void Construct(IInputService inputService) =>
            _inputService = inputService;

        private void Start() =>
            _groundMask = LayerMask.GetMask(Constants.GroundMaskName);

        private void Update()
        {
            var camRay = Camera.main.ScreenPointToRay(_inputService.GetPointerPosition());
            if (!Physics.Raycast(
                    camRay,
                    out var groundHit, 
                    Constants.CamRayLength, 
                    _groundMask)) return;
            _playerToMouse = groundHit.point - transform.position;
            _playerToMouse.y = 0f;
        }

        private void FixedUpdate() =>
            transform.rotation = Quaternion.RotateTowards(
                transform.rotation, 
                Quaternion.LookRotation(_playerToMouse), 
                Speed * Time.deltaTime);
    }
}